package com.nl.controller.web.controller;

import com.github.pagehelper.PageInfo;
import com.nl.controller.common.exception.SmsException;
import com.nl.controller.common.interceptor.SysContext;
import com.nl.controller.common.model.Response;
import com.nl.controller.common.util.ResponseUtil;
import com.nl.controller.web.bean.SmsArtificialRecord;
import com.nl.controller.web.bean.SmsUsers;
import com.nl.controller.web.global.GlobalConst;
import com.nl.controller.web.service.SmsArtificialRecordService;
import com.nl.controller.web.util.FileUtil;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.Map;


@RestController
@Slf4j
@RequestMapping("artificialRecord")
public class SmsArtificialRecordController {
    @Autowired
    private SmsArtificialRecordService smsArtificialRecordService;

    @ApiOperation(value = "初始化批次号", notes = "初始化批次号")
    @PostMapping("initBatchNumber")
    public Response initBatchNumber() {
        String batchNumber;
        batchNumber = smsArtificialRecordService.initBatchNumber();
        log.debug("返回批次号：{}", batchNumber);
        if ("".equals(batchNumber)) {
            return ResponseUtil.error(-1, "获取批次号失败");
        }
        return ResponseUtil.sucess(batchNumber);
    }

    @ApiOperation(value = "模板下载", notes = "模板下载")
    @RequestMapping(value = "/download", method = RequestMethod.GET)
    public void download(HttpServletResponse res) {
        String fileName = "msisdn.csv";
        FileUtil.download(fileName, res);
    }

    //处理文件上传
    @RequestMapping(value = "/upload", method = RequestMethod.POST)
    public Response upload(@RequestParam("file") MultipartFile file,
                           HttpServletRequest request,
                           @RequestParam(value = "cityId", required = false) String cityId,
                           @RequestParam(value = "countyId", required = false) String countyId,
                           @RequestParam(value = "mgrId", required = false) String mgrId,
                           @RequestParam(value = "sendTime", required = false) String sendTime,
                           @RequestParam(value = "mgrNameId", required = false) String mgrNameId,
                           @RequestParam(value = "remark", required = false) String remark,
                           @RequestParam(value = "joinFrequencyRoom", required = false) String joinFrequencyRoom,
                           @RequestParam(value = "batchNumber", required = true) String batchNumber,
                           @RequestParam Map<String, Object> paramMap

    ) {
        HttpSession session = SysContext.getRequest().getSession();
        SmsUsers user = (SmsUsers) session.getAttribute("user");
        String userId = user.getUserId();
        int uploadNumber;

        String path = GlobalConst.FILE_SEND_PATH;
        int sendCountMax=Integer.parseInt("1000");
        String fieName = batchNumber + ".csv";
        String result;
        try {
            //System.out.println("===="+mgrNameId+"=-------------"+mgrId);
            if ("".equals(cityId) || cityId == null) {
                return ResponseUtil.error(-1, "您必须选择一个地市");
            } else if (!checkNull(mgrId,mgrNameId)) {
                return ResponseUtil.error(-1, "您必须选择一个项目名称或者项目简称");
            } else if ("".equals(remark) || remark == null) {
                return ResponseUtil.error(-1, "请添加发送理由");
            }  else if (remark.length()>100) {
                return ResponseUtil.error(-1, "发送理由超出长度限制");
            }else {
                if(checkNull(mgrId,mgrNameId)&&"".equals(mgrId)){
                    mgrId = mgrNameId;
                }else if(checkNull(mgrId,mgrNameId)&&"".equals(mgrNameId)){
                    mgrId=mgrId;
                }else{
                    return ResponseUtil.error(-1, "选择项目名称或者项目简称其中一种即可");
                }

                InputStream inputStream;
                int lineCount=0;
                uploadNumber = smsArtificialRecordService.findLink(mgrId,userId);
                log.info(" 查询已有条数信息：{}", uploadNumber);
                String overExpire="0";

                try {
                    inputStream = file.getInputStream();
                    List<String> list = FileUtil.readCSV(inputStream);
//                    SmsTemplateAttr smsTemplateAttr = smsTemplateAttrService.findTemplateAttrByMgrId(mgrId);
//                    String isLocal=smsTemplateAttr.getIsLocal();
//                    String localDate= smsTemplateAttr.getLocalDate();
//                    String nonLocalDate= smsTemplateAttr.getNonlocalDate();
//
//                    //前台选择了号码加入频次库
//                    if("1".equals(joinFrequencyRoom)){
//                        log.info("该批次人工推送号码 已 选择加入频次库，批次编号："+ batchNumber);
//                    }else{
//                        log.info("该批次人工推送号码 未 选择加入频次库，批次编号："+ batchNumber);
//                    }
//
//                    //设置号码过期时间，本地或者本地加外地 按照本地过期时间，外地就按照外地过期时间
//                    if("0".equals(isLocal)||"2".equals(isLocal)){
//                        if(null != localDate && !"".equals(localDate)){
//                            overExpire = localDate;
//                        }
//                    }else{
//                        if(null != nonLocalDate && !"".equals(nonLocalDate)){
//                            overExpire = nonLocalDate;
//                        }
//                    }

                    lineCount = list.size();
                    if(!("0".equals(user.getDuty())))
                    {
                        if((uploadNumber+lineCount)>sendCountMax)
                        {
                            log.error("该项目每日上传限制"+sendCountMax+"条,已上传"+uploadNumber+"条，请联系省公司");
                            return ResponseUtil.error(-1, "该项目每日上传限制"+sendCountMax+"条,已上传"+uploadNumber+"条，请联系省公司");
                        }
                    }
                } catch (IOException e1) {
                    e1.printStackTrace();
                }

                log.info("remark大小:" + remark.length());
                log.info("文件上传参数:" + paramMap.toString());

                smsArtificialRecordService.addUploadRecord(mgrId, cityId,countyId, sendTime, remark, batchNumber,lineCount,joinFrequencyRoom,overExpire);
                result = FileUtil.fileUpload(file, request, path, fieName);
                if ("success".equals(result)) {
                    log.info("文件上传成功");
                    return ResponseUtil.sucess(result);
                }else {
                    log.info("文件上传失败");
                    return ResponseUtil.error(-1, result);
                }
            }
        } catch (Exception e) {
            log.info("文件上传失败");
            e.printStackTrace();
            return ResponseUtil.error(-1, "文件上传出现异常");
        }
    }



    @ApiOperation(value = "查询手工发送信息", notes = "分页查询手工发送信息")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "limit", value = "每页数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "cityId", value = "城市编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "countyId", value = "区县编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "mgrId", value = "项目编号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "sendTime", value = "发送时间", required = true, dataType = "String"),
            @ApiImplicitParam(name = "batchNumber", value = "批次号", required = true, dataType = "String"),
            @ApiImplicitParam(name = "mgrName", value = "项目名称 ", required = true, dataType = "String")
    })
    @PostMapping("find")
    public Response findSendRecord(
            @RequestParam(value = "page", required = true) int page,
            @RequestParam(value = "limit", required = true) int limit,
            @RequestParam(value = "cityId", required = false) String cityId,
            @RequestParam(value = "countyId", required = false) String countyId,
            @RequestParam(value = "mgrId", required = false) String mgrId,
            @RequestParam(value = "sendTime", required = false) String sendTime,
            @RequestParam(value = "batchNumber", required = false) String batchNumber,
            @RequestParam(value = "mgrName", required = false) String mgrName,
            @RequestParam Map<String, Object> paramMap
    ) {
    	
    	HttpSession session = SysContext.getRequest().getSession();
        SmsUsers user = (SmsUsers) session.getAttribute("user");
        if (cityId == null) {
            throw new SmsException("请选择查询条件，开始查询");
        } else {
            PageInfo<SmsArtificialRecord> pageInfo = smsArtificialRecordService.findUploadRecord(page, limit, cityId,countyId, mgrId, sendTime, batchNumber,mgrName);
            log.info(" 查询手工发送信息：{}", paramMap.toString());
            log.debug("查询手工发送信息返回参数：{}", pageInfo.getList().toString());
            return ResponseUtil.sucess(pageInfo.getList(), pageInfo.getTotal());
        }
    }


    @ApiOperation(value = "查询批次列表", notes = "查询批次列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "mgrId", value = "项目编号", required = true, dataType = "String"),
    })
    @PostMapping("findBatchNumber")
    public Response findBatchNumber(
            @RequestParam(value = "mgrId", required = false) String mgrId
    ) {
        List list = smsArtificialRecordService.findBatchNumberList(mgrId);
        log.info(" 查询手工发送信息：{}", mgrId);
        log.debug("查询手工发送信息返回参数：{}", list.size());
        return ResponseUtil.sucess(list);
    }

    @ApiOperation(value = "查询手工发送结果", notes = "查询手工发送结果")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "batchNumber", value = "批次号", required = true, dataType = "batchNumber"),
    })
    @PostMapping("findResult")
    public Response findResult(
            @RequestParam(value = "batchNumber", required = true) String batchNumber
    ) {
        List list = smsArtificialRecordService.getState(batchNumber);
        log.info(" 查询手工发送结果：{}", batchNumber);
        log.debug("查询手工发送结果返回参数：{}", list.size());
        return ResponseUtil.sucess(list);
    }


    @ApiOperation(value = "查询手工发送信息详情", notes = "分页查询手工发送信息详情")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页码", required = true, dataType = "String"),
            @ApiImplicitParam(name = "limit", value = "每页数量", required = true, dataType = "String"),
            @ApiImplicitParam(name = "batchNumber", value = "批次号", required = true, dataType = "String")
    })
    @PostMapping("detail")
    public Response findSendRecord(
            @RequestParam(value = "page", required = true) int page,
            @RequestParam(value = "limit", required = true) int limit,
            @RequestParam(value = "batchNumber", required = false) String batchNumber
            ) {
        PageInfo<SmsArtificialRecord> pageInfo = smsArtificialRecordService.findSendDeatil(page, limit, batchNumber);
        log.info(" 查询手工发送信息详情：{}", batchNumber);
        log.debug("查询手工发送信息详情返回参数：{}", pageInfo.getList().toString());
        return ResponseUtil.sucess(pageInfo.getList(), pageInfo.getTotal());
    }
    private boolean checkNull(String mgrId,String mgrNameId){
        return (mgrId != null && mgrId != "") || (mgrNameId != null && mgrNameId != "");
    }
}

